﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace FtpCrawler
{
    public class FtpClient
    {
        private string _hostname;
        private string _username;
        private string _encoding;
        private NetworkCredential _credential = null;

        public FtpClient(string hostname, NetworkCredential credential)
        {
            this.Hostname = hostname;
            this.Credential = credential;
            if(credential != null)
            {
                this.Username = credential.UserName;
            } else
            {
                this.Username = "anonymous";
            }
        }

        public NetworkCredential Credential
        {
            get { return _credential; }
            set { _credential = value; }
        }

        public string Hostname
        {
            get { return _hostname; }
            set { _hostname = value; }
        }

        public string Username
        {
            get { return _username; }
            set { _username = value; }
        }

        public string Encoding
        {
            get { return _encoding; }
            set { _encoding = value; }
        }

        /// <summary>
        /// 创建Ftp请求连接
        /// </summary>
        /// <remarks>参考.net sdk sample:FtpExplorer项目Microsoft.Samples.FTPExplorer.FtpClient类中的CreateFtpWebRequest</remarks>
        /// <param name="uri"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public FtpWebRequest CreateFtpWebRequest(Uri uri, string method)
        {
            FtpWebRequest ftpClientRequest = (FtpWebRequest) WebRequest.Create(uri);
            if(this.Credential != null)
            {
                ftpClientRequest.Credentials = this.Credential;
            }
            ftpClientRequest.Method = method;
            // 连接后关闭，否则将会出现
            //      远程服务器返回错误:(550) 文件不可用(例如，未找到文件，无法访问文件)
            // 错误。
            // 参考：http://hi.baidu.com/kidcdf/blog/item/a1cb65ec3851d1d42e2e21e5.html
            ftpClientRequest.KeepAlive = false;
            return ftpClientRequest;
        }
    }
}
